import time

from robot.api import logger

from ..ui.PageElement import PageElement, POLL_FREQUENCY
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.common.keys import Keys

from .Selector import Selector
from ...exception.TestException import TestException
from ...exception.errorcode import ErrorCode


class Input(PageElement):

    def __try_send_keys(self, input_element, value):
        input_element.clear()
        self.blur()
        # 对于antd的input-number，即使clear后，再输入，之前的值还会出来，所以先输入删除
        try:
            input_element.send_keys(Keys.BACKSPACE * 30)
        except Exception as e:
            logger.warn("this input cannot be cleared!")
        time.sleep(1)
        input_element.send_keys(value)
        # self.jquery_input_change()
        self.blur()


    def setValue(self, value):
        # 调度中心项目会报超时
        # input_element = WebDriverWait(self._driver, self._wait_time_out).until(
        #         EC.visibility_of_element_located((Selector.MAP[self._selector_type], self._selector_str)))
        input_element = self._get_present_element(wait_flag=True)

        input_element.clear()
        self.blur()
        # 对于antd的input-number，即使clear后，再输入，之前的值还会出来，所以先输入删除
        try:
            input_element.send_keys(Keys.BACKSPACE*30)
        except Exception as e:
            logger.warn("this input cannot be cleared!")
        input_element.send_keys(value)
        # self.jquery_input_change()
        self.blur()

        num = 2
        while num > 0:
            # 加个检验
            try:
                input_value = input_element.get_attribute('value')
                if input_value != str(value).rstrip():
                    # Modify by james at 20201124, 不报错，只告警
                    # raise TestException.by_error_code(ErrorCode.ELEMENT_OPERATE_FAILED, message='input value: {0}'.format(value))
                    logger.warn(f"the input element text: {input_value} not equal your input value {str(value).rstrip()}.")
                    self.__try_send_keys(input_element, value)
                else:
                    return
            except Exception as e:
                logger.warn("check input result failed  {}".format(str(e)))
            finally:
                num -=1

    def getValue(self):
        """ 当input为disabled时，通过text获取不到内容，所以重写
        """
        self.wait_element_presence()
        element = self._driver.find_element(self._selector_type, self._selector_str)
        return element.text or element.get_attribute("value")


    def wait_element_ready(self, timeout=None, poll_frequency=POLL_FREQUENCY, recheck=True):
        timeout = timeout or self._wait_time_out
        WebDriverWait(self._driver, timeout, poll_frequency).until(
            EC.visibility_of_element_located((Selector.MAP[self._selector_type], self._selector_str)))

    def get_identification(self):
        id = {'tag': ['input']}
        return id
